<template>
    <div class="app-wrapper">
        <div class="banner">
            <div class="banner-file" v-if="filename">
                <i
                    class="el-icon-folder-opened"
                    style="font-size: 25px; margin-right: 5px; color: #e6a23c"
                ></i>
                {{ filename }}
            </div>
            <a href="/" class="banner-title">文档展示器</a>
            <i class="el-icon-full-screen screenfull-style" @click.stop="toFullScreen"></i>
            <div class="banner-right">
                <el-button type="primary" round size="mini" @click="handleupload">
                    上传预览
                </el-button>
                <el-button type="primary" round size="mini" @click="download">下载</el-button>
                <input v-show="false" type="file" ref="fileButton" @change="handleChange" />
            </div>
        </div>
        <div
            class="content"
            ref="screenFullContent"
            v-loading="loading"
            element-loading-text="正在加载中，请耐心等待..."
            element-loading-spinner="el-icon-loading"
            element-loading-background="rgba(0, 0, 0, 0.8)"
        >
            <el-empty v-if="!filename" style="margin-top: 100px">
                <el-button type="primary" round size="mini" @click="handleupload">
                    上传预览
                </el-button>
            </el-empty>
            <!-- <div v-show="loading" ></div> -->
            <div ref="output"></div>
            <a href="https://gitee.com/cj6209577" class="link-style">https://gitee.com/cj6209577</a>
        </div>
    </div>
</template>

<script>
import { getExtend, readBuffer, render, fullScreen, load } from "@/utils/index";
import { parse } from "qs";
import axios from "axios";

/**
 * 支持嵌入式显示，基于postMessage支持跨域
 * 示例代码：
 *
 */
export default {
    name: "main-app",
    props: {
        msg: String
    },
    data() {
        return {
            // 加载状态跟踪
            loading: false,
            // 上个渲染实例
            last: null,
            // 隐藏头部，当基于消息机制渲染，将隐藏
            hidden: false,
            // 使用输入框
            input: false,
            // 浮层显示
            overlay: true,
            // 文件名
            filename: "",
            // 网址
            url: "",
            currentFileContent: null
        };
    },
    created() {
        // 允许使用预留的消息机制发送二进制数据，必须在url后添加?name=xxx.xxx&from=xxx
        const target = parse(location.search?.slice?.(1));
        console.log(target);
        if (target?.url) {
            this.url = target.url;
            this.loadFromUrl();
        }
    },
    methods: {
        // 从url加载
        loadFromUrl() {
            this.loading = true;
            // 要预览的文件地址
            const { url } = this;
            const filename = url.substr(url.lastIndexOf("/") + 1);
            // 拼接iframe请求url
            axios({
                url,
                method: "get",
                responseType: "blob"
            })
                .then(({ data }) => {
                    if (!data) {
                        console.error("文件下载失败");
                    }
                    const file = new File([data], filename, {});
                    this.handleChange({ target: { files: [file] } });
                })
                .finally(() => {
                    this.loading = false;
                });
        },
        async handleChange(e) {
            this.loading = true;
            try {
                const [file] = e.target.files;
                this.currentFileContent = file;
                this.filename = (file.name && decodeURIComponent(file.name)) || "";
                const arrayBuffer = await readBuffer(file);
                this.loading = false;
                this.last = await this.displayResult(arrayBuffer, file);
            } catch (e) {
                console.error(e);
            } finally {
                this.loading = false;
            }
        },
        displayResult(buffer, file) {
            // 取得文件名
            const { name } = file;
            // 取得扩展名
            const extend = getExtend(name);
            // 输出目的地
            const { output } = this.$refs;
            // 生成新的dom
            const node = document.createElement("div");
            // 添加孩子，防止vue实例替换dom元素
            if (this.last) {
                output.removeChild(output.lastChild);
                this.last.$destroy();
            }
            const child = output.appendChild(node);
            // 调用渲染方法进行渲染
            return new Promise((resolve, reject) =>
                render(buffer, extend, child).then(resolve).catch(reject)
            );
        },
        handleupload() {
            this.$refs.fileButton?.click?.();
        },
        //下载附件
        download() {
            load({
                fileName: this.filename,
                file: this.currentFileContent
            }).then(res => {
                console.log(res);
            });
        },
        toFullScreen() {
            fullScreen(this.$refs.screenFullContent);
        }
    }
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.app-wrapper {
    width: 100%;
    height: 100%;
    overflow: hidden;
}
.banner {
    height: 50px;
    width: 100%;
    /* padding: 0 30px; */
    background-color: #323639;
    display: flex;
    justify-content: center;
    align-items: center;
    color: #f2ffff;
    position: relative;

    /* box-shadow: 0 6px 8px 4px #76767614; */
    /* background: white;
  background: linear-gradient(
    to right bottom,
    rgba(255, 255, 255, 0.7),
    rgba(255, 255, 255, 0.3)
  );
  z-index: 2;
  backdrop-filter: blur($blur); */
}
.banner-file {
    padding-left: 10px;
    position: absolute;
    left: 15px;
    top: 15px;
}
.banner-title {
    text-decoration: none;
    color: #ededed;
    font-size: 20px;
    font-weight: bold;
    letter-spacing: 2px;

    font-family: "Lucida Sans", "Lucida Sans Regular", "Lucida Grande", "Lucida Sans Unicode",
        Geneva, Verdana, sans-serif;
}
.banner-right {
    /* padding-left: 20px; */
    position: absolute;
    right: 15px;
    top: 15px;
}
.content {
    height: calc(100vh - 50px);
    width: 100%;
    overflow-y: auto;
    background-color: #525659;
    color: #f2ffff;
}
/* .content-box::after{
  content:'https://gitee.com/cj6209577';
  position: absolute;
  left: 45%;
  top: 97%;
} */
.link-style {
    position: fixed;
    left: 50%;
    bottom: 5px;
    transform: translate(-50%);
    z-index: 99;
    text-decoration: none;
    color: #f2ffff;
    background-color: #525659;
}
.screenfull-style {
    margin-left: 10px;
    font-size: 25px;
}
</style>
